
<template>
    <div class="department" id="department">
      <!-- 左侧部门管理 -->
      <div class="structureTree" v-if="treelength">
        <div class="structureTree_title">
          <div>组织机构</div>
          <div>
            <!-- <el-checkbox v-model="checked" @change="see()">查看下级</el-checkbox> -->
          </div>
        </div>
        <tree
          :treeData="treeData"
          :checkData="checkData"
          nodeKey="fCompanyid"
          @getTreeInfo="handleNodeClick"
          :defaultProps="defaultProps"
        >
        </tree>
      </div>
      <!-- 右侧 -->
      <div class="department_right">
        <!-- 机构名称 -->
        <el-breadcrumb :title="showName"></el-breadcrumb>
        <div class="mechanism_nav">
          <!-- 左侧 -->
          <div class="mechanism_nav_left"></div>
          <!-- 顶部按钮 -->
          <div class="print" style="justify-content: flex-end">
            <el-button
              v-if="userInfo.userId == 'System'"
              type="primary"
              icon="el-icon-circle-plus-outline"
              size="small"
              @click="yj_editForm(0)"
            >
              拌合机绑定</el-button
            >
          </div>
        </div>
        <!-- 顶部导航栏 -->
        <div v-if="!pageFlag" class="networkStatus">
          <div
            class="networkStatusBigBox"
            v-for="(item, index) in tableData"
            :key="index"
            @click="yj_editForm(1, item.F_MachineId)"
          >
            <div class="networkImg">
              <img :src="item.STATUS == 0 ? online2 : online1" alt="" />
            </div>
            <div class="networkInfo">
              <div class="bhClass bhjname">
                {{ item.F_StationName }}-{{ item.F_MachineName }}
              </div>
              <div class="bhClass bhjid">拌合机ID:{{ item.F_MachineId }}</div>
              <div class="bhClass bhjid">拌合站ID:{{ item.F_StationId }}</div>
              <div class="bhClass bhjid">
                上传时间:{{ item.F_DischargeDates }}
              </div>
            </div>
            <div class="btn">
              <!-- 0:停用 1：启用 -->
              <el-switch
                :value="item.F_ActiveStatus | status"
                :active-text="
                  item.F_ActiveStatus == 0
                    ? '停用'
                    : item.F_ActiveStatus == 1
                    ? '启用'
                    : '未启用'
                "
              >
              </el-switch>
            </div>
          </div>
        </div>
        <div v-if="pageFlag" class="pageFlag">
          <img src="@/assets/img/undata.png" alt="" />
          <div class="pageFlagText">暂时没有数据哦！</div>
        </div>
      </div>
  
      <!-- 绑定拌合机弹框 -->
      <div class="Control-1 mechanism_dialogS">
        <el-dialog
          title="新增"
          :modal-append-to-body="false"
          v-dialogDrag
          :visible.sync="dialogVisible"
          v-loading="loadingDialog"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.2)"
        >
          <div class="dialogBody common" :style="{ height: '550px' }">
            <noData v-if="machineList.length == 0"></noData>
            <div v-else class="addMemberCheckLeft addMachine">
              <el-checkbox-group
                v-model="checkMachine"
                @change="selectMachine($event)"
              >
                <el-checkbox-button
                  v-for="item in machineList"
                  :label="item.F_MachineId"
                  :key="item.F_MachineId"
                  :value="item.F_MachineName"
                >
                  <div class="addMemberCheck">
                    <div class="MemberIcon">机</div>
                    <div class="MemberDetailInfos">
                      <div class="name">
                        {{ item.F_MachineName }}/{{ item.F_StationName }}
                      </div>
                      <div class="hostName">{{ item.F_MachineId }}</div>
                    </div>
                  </div>
                </el-checkbox-button>
              </el-checkbox-group>
              <!-- </div> -->
            </div>
            <div v-if="machineList.length != 0" class="newlyAdded_btn">
              <el-button type="primary" @click="yj_saveObjectForm(0)"
                >保存</el-button
              >
              <el-button type="warning" @click="dialogVisible = false"
                >关闭</el-button
              >
            </div>
          </div>
        </el-dialog>
      </div>
      <!-- 点击拌和机详情 -->
      <div class="Control-1 bansetting" id="smallDialog">
        <el-dialog
          title="修改"
          :modal-append-to-body="false"
          v-dialogDrag
          :visible.sync="dialogMachineIdVisible"
          v-loading="loadingMachineIdDialog"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.2)"
        >
          <div class="dialogBody common" :style="{ height: '400px' }">
            <div style="height: 160px">
              <publicForm
                ref="ObjectForm"
                lableWidth="60px"
                :formObj="formObj"
                :formData="formData"
              >
              </publicForm>
            </div>
          </div>
          <div class="newlyAdded_btn">
            <el-button type="primary" @click="yj_saveObjectForm(1)"
              >保存</el-button
            >
            <el-button type="warning" @click="dialogMachineIdVisible = false"
              >关闭</el-button
            >
          </div>
        </el-dialog>
      </div>
    </div>
  </template>
  
  <script>
  import tree from "@/components/public/el-trees"; //左侧机构树
  import elBreadcrumb from "@/components/public/el-breadcrumb.vue"; //面包屑
  import publicForm from "@/components/public/el-form.vue";
  import noData from "@/components/public/noData.vue";
  import {
    getUserCompanyTreeList, //左侧机构树接口
    getMachineList, // 新增按钮拌合机状态
    getMachineStatus, // 拌合机在线状态
    addMachineActive, // 保存按钮拌合机状态
    updateMachineActive, // 修改 启用停用/开始上传日期
    getMachineActive, // 获取 拌合机状态详情
  } from "@/api/request.js";
  export default {
    name: "networkStatus",
    data() {
      return {
        name: "networkStatus", //按钮配置页面代号
        highlightBd: true, //左侧机构树停留背景色
        online2: require("@/assets/img/tong/icon_sw_online2.png"),
        online1: require("@/assets/img/tong/icon_sw_online1.png"),
        treelength: false, //左侧树显示隐藏
        checked: true, //查看下级按钮
        showName: "未选择公司",
        loadingDialog: false, //拌合机绑定loading
        dialogVisible: false, //拌合机绑定dialog
        loadingMachineIdDialog: false, //拌合机详情loading
        dialogMachineIdVisible: false, //拌合机详情dialog
        machineList: [], //拌合机列表
        checkMachine: [],
        selectMachineList: [], //选择绑定拌和机数组
        formData: {
          fCompanyid: "", // 施工标段id
          fMachineid: "", // 拌合机编号/id
          fDischargedates: "", // 开始上传时间
          fActivestatus: "", // 上传启用停用 1-启用 0-停用
          userName: this.$store.state.userInfo.realName, // 当前登陆人名称
          userId: this.$store.state.userInfo.userId, // 当前登陆人id
          fLongitude: "", //经度
          fLatitude: "", //纬度
        //   fType:2
        }, //部门 新增编辑向后台传递对象
        formObj: [
          //新增编辑配置参数
          {
            input: true, //是input
            label: "拌合机编号",
            prop: "fMachineid",
            width: 24, //参考el-col
            disabled: true,
          },
          {
            dateTime: true,
            label: "上传时间",
            prop: "fDischargedates",
            placeholder: "请选择",
            width: 24, //参考el-col
            disabled: false,
            rules: [
              {
                required: true,
                message: "请选择上传时间",
              },
            ], //验证
          },
          {
            input: true, //是input
            label: "经度",
            prop: "fLongitude",
            width: 12, //参考el-col
            disabled: false,
            rules: [
              {
                required: true,
                message: "请填写经度",
              },
            ], //验证
          },
          {
            input: true, //是input
            label: "纬度",
            prop: "fLatitude",
            width: 12, //参考el-col
            disabled: false,
            rules: [
              {
                required: true,
                message: "请填写纬度",
              },
            ], //验证
          },
  
          {
            //新增编辑配置参数
            radio: true,
            label: "是否启用",
            prop: "fActivestatus",
            placeholder: "请选择",
            width: 24, //参考el-col
            disabled: false,
            options: [
              {
                label: "启用",
                value: "1",
              },
              {
                label: "停用",
                value: "0",
              },
            ],
          },
        ],
        fId: null, //点击当前列表数据fId
        listLoading: false, //列表数据加载loading
        // 列表给后端传参
        getList: {
          // companyId: "", // 施工标段id
          companyId: "", // 施工标段id
          startDates: "", // 开始时间
          endDates: "", // 截至时间
          machineId: "", // 拌和机编号
          enCode: "",
        },
        pageFlag: true,
        companyTree: "", //所有数据
        treeData: [], //左侧树状图数据
        tableData: [], //拌合站数据
        // 左侧机构树
        defaultProps: {
          children: "children",
          label: "fShortname",
        },
        checkData: [],
        userInfo: {}, //登录用户
        treeText: {
          //树状图参数
          companyId: null,
          userId: null,
          text: null,
        },
      };
    },
    components: {
      tree, //左侧组织机构数
      elBreadcrumb, //面包屑
      publicForm,
      noData,
    },
    filters: {
      status(data) {
        var status;
        if (data == 1) {
          status = true;
        } else if (data == 0) {
          status = false;
        }
        return status;
      },
    },
    mounted() {
      this.userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
      console.log(this.userInfo);
      if (JSON.parse(sessionStorage.getItem("getLists"))) {
        var data = JSON.parse(sessionStorage.getItem("getLists"));
        this.getList.companyId = data.fCompanyid; // 施工标段id
        this.getList.startDates = data.startDates; // 开始时间
        this.getList.endDates = data.endDates; // 截至时间
        this.getList.machineId = data.machineId; // 拌和机编号
      }
  
      if (JSON.parse(sessionStorage.getItem("treeCheck"))) {
        var id = JSON.parse(sessionStorage.getItem("treeCheck"));
        this.checkData = [id.fCompanyid];
      }
      this.getTree();
      this.btnRole(this.name);
    },
  
    methods: {
      btnRole(name) {
        // 按钮权限
        var btnList = [];
        var ModuleList = JSON.parse(sessionStorage.getItem("ModuleList"));
        if (ModuleList.length > 0) {
          ModuleList.map((item) => {
            if (item.fEncode == name) {
              btnList = item.modulebuttonList;
            }
          });
          var btnStr = [];
          btnList.map((item) => {
            btnStr.push(item.fEncode);
          });
          // this.yj_view = btnStr.includes("yj_view");
        } else {
          // this.yj_view = true;
        }
      },
  
      // 左侧树结构
      getTree() {
        this.treeText = {
          companyId: this.userInfo.companyId,
          userId: this.userInfo.userId,
          text: "2", // 0其他  1 砼拌合站 2水稳 3沥青
        };
        getUserCompanyTreeList(this.treeText)
          .then((res) => {
            if (res.errcode == 0) {
              var companyTree = res.data.userCompanyTreeList;
              this.treeData = this.commonJs.tranListToTreeData(companyTree);
  
              if (this.treeData[0].children == undefined) {
                this.treelength = false; //左侧组织机构是否显示
              } else {
                this.treelength = true;
              }
  
              if (this.checkData[0]) {
                this.showName = JSON.parse(
                  sessionStorage.getItem("treeCheck")
                ).fShortname;
  
                this.getList.companyId = this.checkData[0];
              } else {
                this.checkData[0] = this.treeData[0].fCompanyid;
                this.showName = this.treeData[0].fShortname; //当前点击组织机构名称
                this.getList.companyId = this.treeData[0].fCompanyid; //当前点击组织机构ID
              }
  
              this.yj_searchForm(this.getList); // 调用主页面列表接口
  
              // 列表
            } else {
              this.$message.error(res.msg);
              // this.$message.error("获取组织机构失败");
              return false;
            }
          })
          .catch(() => {
            return false;
          });
      },
  
      // 点击左侧机构树
      handleNodeClick(data) {
        this.showName = data.fShortname; //顶部显示机构名
        this.getList.companyId = data.fCompanyid;
        var time = new Date();
        const y = time.getFullYear();
        const m = (time.getMonth() + 1 + "").padStart(2, "0");
        const d = (time.getDate() + "").padStart(2, "0");
        const hh = (time.getHours() + "").padStart(2, "0");
        const mm = (time.getMinutes() + "").padStart(2, "0");
        const ss = (time.getSeconds() + "").padStart(2, "0");
        var date = new Date();
        var base = Date.parse(date); // 转换为时间戳
        var oneDay = 24 * 3600 * 1000;
        var daytimeArr = [];
        for (var i = 1; i < 7; i++) {
          //前七天的时间
          var now = new Date((base -= oneDay));
          var myear = now.getFullYear();
          var month = now.getMonth() + 1;
          var mday = now.getDate();
          daytimeArr.push(
            [
              myear,
              month >= 10 ? month : "0" + month,
              mday >= 10 ? mday : "0" + mday,
            ].join("-")
          );
        }
        this.getList.startDates = daytimeArr[5] + " " + `00:00:00`; // 开始时间
        this.getList.endDates = `${y}-${m}-${d} ${hh}:${mm}:${ss}`; // 截至时间
  
        this.getList.machineId = ""; // 拌和机编号
  
        this.value2 = [
          daytimeArr[5] + " " + "00:00:00",
          `${y}-${m}-${d} ${hh}:${mm}:${ss}`,
        ];
  
        this.yj_searchForm(this.getList);
      },
  
      // 获取列表数据
      yj_searchForm(data) {
        this.listLoading = true;
        window.sessionStorage.setItem("getLists", JSON.stringify(data));
        var sc = {
          fCompanyid: data.companyId, // 施工标段id
          fType:"2"
        };
  
        getMachineStatus(sc)
          .then((res) => {
            if (res.errcode == 0) {
              var that = this;
              that.listLoading = false;
              if (res.data.length > 0) {
                this.tableData = res.data;
                this.pageFlag = false;
              } else {
                this.pageFlag = true;
                // console.log("暂无数据");
              }
            } else {
              this.$message.error(res.msg);
              return false;
            }
          })
          .catch((error) => {
            console.log(error);
          });
      },
      // 绑定拌和机保存接口
      yj_saveObjectForm(num) {
        if (num == 0) {
          //绑定拌合机
          if (this.selectMachineList.length > 0) {
            addMachineActive({ machineIds: this.selectMachineList}).then(
              (res) => {
                if (res.errcode == 0) {
                  this.dialogVisible = false;
                  this.yj_searchForm(this.getList);
                  this.$message.success("绑定成功");
                  this.checkMachine = [];
                } else {
                  console.log("绑定拌和机保存接口报错");
                }
              }
            );
          } else {
            this.$message.warning("请选择需要绑定的拌和机");
          }
        } else if (num == 1) {
          this.formData.fCompanyid = this.getList.companyId;
          if (this.$refs.ObjectForm.submitForm()) {
            updateMachineActive(this.formData)
              .then((res) => {
                if (res.errcode == 0) {
                  this.yj_searchForm(this.getList);
                  this.dialogMachineIdVisible = false;
                  this.$message.success("修改成功");
                } else {
                  this.$message.error(res.msg);
                  console.log("接口报错");
                }
              })
              .catch((error) => {
                console.log("拌合站设置-新增）", error);
              });
          } else {
            console.log("error");
          }
        }
      },
      // 新增编辑
      yj_editForm(num, machineId) {
        if (this.userInfo.userId == "System") {
          if (num == 0) {
            // 打开绑定拌和机弹框
            this.loadingDialog = true;
            this.dialogVisible = true;
  
            getMachineList({ fCompanyid: this.getList.companyId,fType:"2"  }).then((res) => {
              if (res.errcode == 0) {
                this.loadingDialog = false;
                this.machineList = res.data;
              } else {
                console.log("获取拌和机列表接口报错");
              }
            });
          } else if (num == 1) {
            this.dialogMachineIdVisible = true;
            this.loadingMachineIdDialog = true;
            getMachineActive({ machineId: machineId }).then((res) => {
              if (res.errcode == 0) {
                this.loadingMachineIdDialog = false;
                this.formData = res.data;
                if (this.formData.fLatitude == null) {
                  this.formData.fLatitude = "";
                }
                 if (this.formData.fLongitude == null) {
                  this.formData.fLongitude = "";
                }
  
              } else {
                console.log("获取拌和机列表接口报错");
              }
            });
          }
        }
      },
      // 点击拌和机得到拌和机machineId数组
      selectMachine(e) {
        this.selectMachineList = e;
      },
    },
  };
  </script>
  
  <style scoped lang="less">
  .networkStatus {
    // background: pink;
    flex: 1;
    padding: 10px;
    display: flex;
    flex-wrap: wrap;
    box-sizing: border-box;
    min-width: 740px;
    align-content: flex-start;
  
    .networkStatusBigBox {
      background-color: #fafafa;
      border: 1px solid #ccc;
      height: 32.6%;
      height: 35%;
  
      // height: 100rpx;
      // 每个元素都要设置右边距margin-right（每个元素的左右间隙）
      // 同时设置下边距margin-bottom（每个元素的上下间隙）
      margin: 0 10px 10px 0;
      width: calc((100% - 40px) / 5);
      // 这里一行显示4个，所以是/4，一行显示几个就除以几
      // 这里的60rpx = (分布个数4-1)*间隙20rpx, 可以根据实际的分布个数和间隙区调整
      min-width: calc((100% - 40px) / 5);
      max-width: calc((100% - 40px) / 5);
      border-radius: 10px;
      box-sizing: border-box;
      padding: 10px 15px;
      display: flex;
      flex-direction: column;
  
      .networkImg {
        // height: 150px;
        height: 45%;
        // background: pink;
        display: flex;
        justify-content: center;
        align-items: center;
  
        img {
          width: 100%;
          min-width: 30%;
          min-height: 80%;
          max-height: 90%;
          // width: 30%;
          // min-width: 30%;
          // min-height: 60%;
          // max-height: 90%;
        }
      }
  
      .networkInfo {
        height: 40%;
        border-bottom: 1px solid #eee;
        // background: red;
        font-size: 12px;
        padding: 0;
        display: flex;
        flex-direction: column;
  
        .bhClass {
          display: flex;
          // justify-content: center;
          align-items: center;
          height: 25%;
  
          overflow: hidden; //（文字长度超出限定宽度，则隐藏超出的内容）
          white-space: nowrap; //（设置文字在一行显示，不能换行）
          text-overflow: ellipsis; //（规定当文本溢出时，显示省略符号来代表被修剪的文本）
        }
  
        .bhjname {
          color: #171a1d;
          font-weight: 700;
          font-size: 0.16rem;
        }
  
        .bhjid {
          color: #858687;
  
          font-size: 0.14rem;
          // line-height: 1;
          // height: 0.23rem;
          height: 25%;
        }
      }
  
      .btn {
        height: 15%;
        font-size: 0.14rem;
      }
  
      // 每行最右侧的那个不设置右外边距
      &:nth-child(5n + 5) {
        margin-right: 0;
      }
  
      &:hover {
        /* 盒子向上移动 */
        transform: translateY(-1px);
        /* 背景 */
        box-shadow: 0 20px 80px rgba(48, 49, 51, 0.15);
      }
    }
  }
  
  .addMemberCheckLeft {
    width: 98%;
    padding: 0 0 0 20px;
    // border-top: 1px solid rgba(221, 221, 221, 1);
    // border-bottom: 1px solid rgba(221, 221, 221, 1);
    // border-right: 1px solid rgba(221, 221, 221, 1);
  
    .addMemberCheck {
      width: 233px;
      height: 64px;
      border-radius: 2px;
      display: flex;
      align-items: center;
      position: absolute;
      top: 0;
      left: 0;
    }
  }
  
  .addMemberCheck .MemberIcon {
    /* height: 100%; */
    /* height: 54px; */
    height: 62px;
    width: 64px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 28px;
    color: #fff;
    // margin-right: 8px;
    background: rgba(224, 224, 224, 1);
  }
  
  // .MemberIcon img {
  //     width: 37.81px;
  //     height: 39.38px;
  //     border-radius: 50%;
  // }
  
  .MemberDetailInfos {
    position: relative;
    flex: 1;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    overflow: hidden;
  
    .name {
      color: rgba(51, 51, 51, 1);
      font-size: 12px;
      height: 20px;
      line-height: 20px;
    }
  
    .hostName {
      color: rgba(128, 125, 125, 1);
      font-size: 12px;
      height: 20px;
      line-height: 20px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
  
  .MemberIcon .name {
    color: rgba(51, 51, 51, 1);
    font-size: 12px;
    height: 20px;
  
    line-height: 20px;
  }
  
  .MemberIcon .hostName {
    color: rgba(128, 125, 125, 1);
    font-size: 12px;
    height: 20px;
    line-height: 20px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  
  .pageFlag {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
  
    justify-content: center;
    align-items: center;
    color: #171a1d;
    font-size: 16px;
    // background: pink;
  
    img {
      width: 258px;
      height: 208px;
    }
  
    .pageFlagText {
      margin-top: 33px;
    }
  
    .pageFlagTexts {
      font-size: 14px;
      color: #a2a4a7;
    }
  }
  
  .addMachine /deep/.el-checkbox-button {
    width: 235px;
    height: 64px;
  }
  
  #smallDialog /deep/.el-dialog {
    width: 700px !important;
  }
  </style>
  